package vuelos;


import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.ListModel;
import javax.swing.SpinnerListModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import sun.util.calendar.BaseCalendar.Date;

public class VentanaEmpleado {

	//Set Look & Feel
	{
		try {
			javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	private JFrame winemp;
	private JLabel origLabel;
	private JLabel destLabel;
	private JButton searchButton;
	private JComboBox origYear;
	private JComboBox origMonth;
	private JComboBox origDay;
	private JComboBox destYear;
	private JComboBox destMonth;
	private JComboBox destDay;
	private JLabel destDate;
	private JLabel origDate;
	private JLabel gfLabel;
	private JLabel bfLabel;
	private JScrollPane vueltaPane;
	private JScrollPane idaPane;
	private  JCheckBox fullCheckBox;
	private JComboBox destComboBox;
	private JComboBox origComboBox;
	private JButton closeButton;
	private JButton reservaButton;
	protected Connection link;
	private Statement stmt;
	private JTable idaTable;
	private JTable vueltaTable;
	private String flight_date;
	private String flight_dated;
	private String avAirport;
	private String avAirportd;
	private String ClaseIda;
	private String ClaseVuelta;
	private String usuario;
	
	private boolean idaYVuelta;
	
	public VentanaEmpleado( Connection c, String user ){
		initEmployers();
		c = link;
		usuario = user;
	}
	
	private void initEmployers() {
		try {
			winemp = new JFrame();
			winemp.getContentPane().setLayout(null);
			winemp.setBounds(21, 1, 656, 547);
			winemp.setTitle("Empleados");
			winemp.setVisible(true);

			{
				closeButton = new JButton();
				winemp.getContentPane().add(closeButton);
				closeButton.setText("Cerrar");
				closeButton.setBounds(519, 484, 115, 27);
				closeButton.addMouseListener(new MouseAdapter() {
					public void mouseClicked(MouseEvent evt) {
						closeButtonMouseClicked(evt);
					}
				});
			}
			
			{
				reservaButton = new JButton();
				winemp.getContentPane().add(reservaButton);
				reservaButton.setText("Reservar");
				reservaButton.setBounds(395, 484, 115, 27);
				reservaButton.addMouseListener(new MouseAdapter() {
					public void mouseClicked(MouseEvent evt) {
						reservaButtonMouseClicked(evt);
					}
				});
			}
			
			
			{
				origLabel = new JLabel();
				winemp.getContentPane().add(origLabel);
				origLabel.setText("Origen:");
				origLabel.setBounds(12, 12, 55, 14);
			}
			{
				ComboBoxModel origComboBoxModel =
					new DefaultComboBoxModel(
							new String[] {  });
				origComboBox = new JComboBox();
				winemp.getContentPane().add(origComboBox);
				origComboBox.setModel(origComboBoxModel);
				origComboBox.setBounds(59, 9, 196, 20);
				origComboBox.setFont(new java.awt.Font("AlArabiya",0,10));
			}
			{
				destLabel = new JLabel();
				winemp.getContentPane().add(destLabel);
				destLabel.setText("Destino:");
				destLabel.setBounds(258, 12, 65, 14);
			}
			{
				ComboBoxModel destComboBoxModel =
					new DefaultComboBoxModel(
							new String[] {  });
				destComboBox = new JComboBox();
				winemp.getContentPane().add(destComboBox);
				destComboBox.setModel(destComboBoxModel);
				destComboBox.setBounds(308, 9, 223, 20);
				destComboBox.setFont(new java.awt.Font("AlArabiya",0,10));
			}
			{
				fullCheckBox = new JCheckBox();
				winemp.getContentPane().add(fullCheckBox);
				fullCheckBox.setText("Ida y vuelta.");
				fullCheckBox.setBounds(537, 9, 97, 21);
				fullCheckBox.addChangeListener(new ChangeListener() {						
					public void stateChanged(ChangeEvent changeEvent) {
				        AbstractButton abstractButton = (AbstractButton)changeEvent.getSource();
				        ButtonModel buttonModel = abstractButton.getModel();
				        boolean selected = buttonModel.isSelected();
				        idaYVuelta= selected;
				        
				        vueltaTable.setEnabled(selected);
				        vueltaPane.setEnabled(selected);					        
				        bfLabel.setEnabled(selected);					        
				        destDate.setEnabled(selected);
				        destDay.setEnabled(selected);
				        destMonth.setEnabled(selected);
				        destYear.setEnabled(selected);
					}
				});
			}
			{
				searchButton = new JButton();
				winemp.getContentPane().add(searchButton);
				searchButton.setText("Buscar vuelos");
				searchButton.setBounds(519, 32, 115, 27);
				searchButton.addMouseListener(new MouseAdapter() {
					public void mouseClicked(MouseEvent evt) {
						jButton1MouseClicked(evt);
					}
				});
			}
			{
				idaPane = new JScrollPane();
				winemp.getContentPane().add(idaPane, BorderLayout.CENTER);
				idaPane.setBounds(12, 104, 622, 180);

					    {
				       idaTable = new JTable();
				       BorderLayout idaTableLayout = new BorderLayout();
				       idaTable.setLayout(idaTableLayout);
				       idaPane.setViewportView(idaTable);
				       //idaTable.setAutoCreateRowSorter(true);
				       idaTable.setBounds(12, 187, 622, 180);
				       idaTable.setPreferredSize(new java.awt.Dimension(598, 173));
				       idaTable.addMouseListener(new MouseAdapter() {
				    	   public void mouseClicked(MouseEvent evt) {
				    		   idaTableMouseClicked(evt);
				    	   }
				       });
				    }
			}
			{
				vueltaPane = new JScrollPane();
				winemp.getContentPane().add(vueltaPane, BorderLayout.CENTER);
				vueltaPane.setBounds(12, 304, 622, 180);

					    {
				       vueltaTable = new JTable();
				       BorderLayout vueltaTableLayout = new BorderLayout();
				       vueltaTable.setLayout(vueltaTableLayout);
				       vueltaPane.setViewportView(vueltaTable);
				       //vueltaTable.setAutoCreateRowSorter(true);
				       vueltaTable.setBounds(12, 387, 622, 180);
				       vueltaTable.setPreferredSize(new java.awt.Dimension(616, 173));
				       vueltaTable.addMouseListener(new MouseAdapter() {
				    	   public void mouseClicked(MouseEvent evt) {
				    		   vueltaTableMouseClicked(evt);
				    	   }
				       });
				    }
			}

			{
				bfLabel = new JLabel();
				winemp.getContentPane().add(bfLabel);
				bfLabel.setText("Vuelos de vuelta:");
				bfLabel.setBounds(12, 290, 98, 14);
			}
			{
				gfLabel = new JLabel();
				winemp.getContentPane().add(gfLabel);
				gfLabel.setText("Vuelos de ida:");
				gfLabel.setBounds(12, 90, 81, 14);
			}
			{
				origDate = new JLabel();
				winemp.getContentPane().add(origDate);
				origDate.setText("Fecha salida:");
				origDate.setBounds(12, 38, 90, 15);
			}
			{
				destDate = new JLabel();
				winemp.getContentPane().add(destDate);
				destDate.setText("Fecha regreso:");
				destDate.setBounds(258, 38, 94, 15);
			}
			{
				origDay = new JComboBox();
				winemp.getContentPane().add(origDay);
				origDay.setBounds(92, 37, 48, 18);
			}
			{
				origMonth = new JComboBox();
				winemp.getContentPane().add(origMonth);
				origMonth.setBounds(140, 37, 48,18);
			}
			{
				origYear = new JComboBox();
				winemp.getContentPane().add(origYear);
				origYear.setBounds(188, 37, 58, 18);
			}

			{
				destDay = new JComboBox();
				winemp.getContentPane().add(destDay);
				destDay.setBounds(342, 36, 48, 18);
			}
			{
				destMonth = new JComboBox();
				winemp.getContentPane().add(destMonth);
				destMonth.setBounds(390, 36, 48, 18);
			}
			{
				destYear = new JComboBox();
				winemp.getContentPane().add(destYear);
				destYear.setBounds(438, 36, 58, 18);
			}

			connect();
			loadComboboxes();
			fillSpinners();
			idaTable.setEnabled(false);
			vueltaTable.setEnabled(false);

			boolean selected= false;
			idaYVuelta= selected;
	        vueltaTable.setEnabled(selected);
	        vueltaPane.setEnabled(selected);					        
	        bfLabel.setEnabled(selected);					        
	        destDate.setEnabled(selected);
	        destDay.setEnabled(selected);
	        destMonth.setEnabled(selected);
	        destYear.setEnabled(selected);				
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	private void fillSpinners() {
		int i;
		for (i=1; i<=31; i++) {
			origDay.addItem(i);
			destDay.addItem(i);
		}
		for (i=1; i<=12; i++) {
			origMonth.addItem(i);
			destMonth.addItem(i);
		}
		for (i=2009; i<=2015; i++) {
			origYear.addItem(i);
			destYear.addItem(i);
		}
	}

	private void connect(){
		if (this.link == null)
	      {
	         try
	         {
	            Class.forName("com.mysql.jdbc.Driver").newInstance();
	         }
	         catch (Exception ex)
	         {
	            System.out.println(ex.getMessage());
	         }
	         try
	         {
	        	 String servidor = "localhost:3306";
		         String baseDatos = "vuelos";
		         String usuario = "empleado";
		         String clave = "empleado";
		         String urlConexion = "jdbc:mysql://" + servidor + "/" + baseDatos;
		         this.link = DriverManager.getConnection(urlConexion, usuario, clave);
	         }
	         catch (SQLException ex)
	         {
	        	System.out.println("Problema de autenticación en la base de datos.");
	            System.out.println("SQLException: " + ex.getMessage());
	            System.out.println("SQLState: " + ex.getSQLState());
	            System.out.println("VendorError: " + ex.getErrorCode());
	         }
	      }
	}
	private void loadComboboxes() {

		try
		{
		String Consulta = "SELECT nombre,ciudad FROM aeropuertos";
		stmt = link.createStatement();
		ResultSet result = stmt.executeQuery(Consulta);
		while (result.next()){
			String txt = result.getString("ciudad") + ", " + result.getString("nombre");
			origComboBox.addItem(txt);
			destComboBox.addItem(txt);
				}


		stmt.close();
		}
		catch(SQLException error)
		{
			System.out.println("Error en consulta de listado de tablas.");
		}
	}

	public void setClaseIda(String C){
			ClaseIda = C;
	}
	public void setClaseVuelta(String C){
		ClaseVuelta = C;
}
	
	
	private void closeButtonMouseClicked(MouseEvent evt) {
		winemp.setVisible(false);
		winemp.dispose();
		this.disconnect();
		new Principal();
	}

	private void reservaButtonMouseClicked(MouseEvent evt) {
		new SelectPassenger(this);
	}
	
	private void jButton1MouseClicked(MouseEvent evt) {
		try
		{
		DefaultTableModel cls = new DefaultTableModel();
		idaTable.setModel(cls);
		vueltaTable.setModel(cls);
		idaTable.setEnabled(true);
		flight_date = origYear.getSelectedItem().toString() + "-" + origMonth.getSelectedItem().toString() + "-" + origDay.getSelectedItem().toString();
		flight_dated = destYear.getSelectedItem().toString() + "-" + destMonth.getSelectedItem().toString() + "-" + destDay.getSelectedItem().toString();
		String[] airport = origComboBox.getSelectedItem().toString().split(", ");
		String[] airportd = destComboBox.getSelectedItem().toString().split(", ");
		String Consulta = "	SELECT vuelo_numero AS vuelo, origen_cod, hr_salida, destino_cod, hr_llegada, vd.modelo_avion AS modelo, duracion AS 'Tiempo estimado' "
						+ " FROM vuelos_disponibles vd JOIN salidas s ON vd.vuelo_numero=s.vuelo " 
						+ " WHERE (vuelo_fecha='"+flight_date +"' AND origen_ciudad='"+ airport[0].toString()+"' AND destino_ciudad='"+ airportd[0].toString() +"') "
						+ " GROUP BY vuelo_numero";
		//System.out.println(Consulta);
		stmt = link.createStatement();
		ResultSet rs = stmt.executeQuery(Consulta);
		ResultSetMetaData rsmd = rs.getMetaData();
        ConsultasTableModel modelo = new ConsultasTableModel();
        for (int i = 1; i <= rsmd.getColumnCount(); i++)
         {
            String columnaNombre = rsmd.getColumnLabel(i);
            Class columnaTipo = Class.forName(rsmd.getColumnClassName(i));
            boolean columnaEditable = false;
            modelo.agregarColumna(columnaNombre, Class.forName("java.lang.String"), columnaEditable);
         }

         idaTable.setModel(modelo);


		while (rs.next())
        {
           Vector<Object> fila = new Vector<Object>();
           for (int j = 1; j <= rsmd.getColumnCount(); j++)
           {
              fila.add(rs.getObject(j));
           }
           ((ConsultasTableModel) this.idaTable.getModel()).addRow(fila);
        }


		//Ida y vuelta check.
		if (fullCheckBox.isSelected()) {
			vueltaTable.setEnabled(true);
			String Consultad = "SELECT `Codigo vuelo` as 'Vuelo',`Aeropuerto salida`, `Hora salida`,`Aeropuerto destino`, `Hora Arrivo`,`modelo_avion` as 'Modelo avion' FROM vuelos_disponibles JOIN salidas ON `Codigo Vuelo`=vuelo WHERE (fecha='"+flight_dated +"' AND `Aeropuerto Salida`='"+ airportd[1].toString()+"' AND `Aeropuerto destino`='"+ airport[1].toString() +"') GROUP By `Codigo Vuelo`";
			stmt = link.createStatement();
			rs = stmt.executeQuery(Consultad);
			rsmd = rs.getMetaData();
	        modelo = new ConsultasTableModel();
	        for (int i = 1; i <= rsmd.getColumnCount(); i++)
	         {
	            String columnaNombre = rsmd.getColumnLabel(i);
	            Class columnaTipo = Class.forName(rsmd.getColumnClassName(i));
	            boolean columnaEditable = false;
	            modelo.agregarColumna(columnaNombre, columnaTipo, columnaEditable);
	         }
	         vueltaTable.setModel(modelo);

			while (rs.next())
	        {
	           Vector<Object> fila = new Vector<Object>();
	           for (int j = 1; j <= rsmd.getColumnCount(); j++)
	           {
	              fila.add(rs.getObject(j));
	           }
	           ((ConsultasTableModel) this.vueltaTable.getModel()).addRow(fila);
	        }
		}
		else
		{
		vueltaTable.setEnabled(false);
		}

		stmt.close();
		}
		catch(SQLException error)
		{
			System.out.println("Error en consulta de listado de tablas.");
		}
		catch (ClassNotFoundException e)
	    {
	        e.printStackTrace();
	    }
	}

	private void idaTableMouseClicked(MouseEvent evt) {
		if ((idaTable.isEnabled() == true)  &&  ( idaTable.getRowCount() != 0 )) {
		String vuelo = idaTable.getValueAt(0, idaTable.getSelectedRow()).toString();
		String values[] = { vuelo, flight_date };
		Disponibilidad av = new Disponibilidad(link,values,this,true);
		}
	}

	  private void disconnect()
	   {
	      if (this.link != null)
	      {
	         try
	         {
	            this.link.close();
	            this.link = null;
	         }
	         catch (SQLException ex)
	         {
	            System.out.println("SQLException: " + ex.getMessage());
	            System.out.println("SQLState: " + ex.getSQLState());
	            System.out.println("VendorError: " + ex.getErrorCode());
	         }
	      }
	   }

	  private void vueltaTableMouseClicked(MouseEvent evt) {
				if ((vueltaTable.isEnabled() == true)  &&  ( vueltaTable.getRowCount() != 0 )) {
				String vuelo = vueltaTable.getValueAt(0, vueltaTable.getSelectedRow()).toString();
				String values[] = { vuelo, flight_dated };
				Disponibilidad av = new Disponibilidad(link,values,this,false);
				}
			}

	 /* IN in_vuelo VARCHAR(40), */
	   public String getVueloIda() {
		   return idaTable.getValueAt(idaTable.getSelectedRow(),0).toString(); 
	   }
	  /* IN in_fecha DATE, */	
	   public String getDateIda() {
		   return origYear.getSelectedItem().toString() + "-" + origMonth.getSelectedItem().toString() + "-" + origDay.getSelectedItem().toString();
	   }
	  /* IN in_clase VARCHAR(40),*/
	   public String getClaseIda() {
		   return ClaseIda;			   
	   }
	  /* IN in_legajo INT(10) UNSIGNED,*/
	  public String getLegajoEmpleado() {
		  return usuario;
	  }
	  
	  /* IN in_vuelo VARCHAR(40), */
	   public String getVueloVuelta() {
		   return vueltaTable.getValueAt(vueltaTable.getSelectedRow(),0).toString(); 
	   }
	  /* IN in_fecha DATE, */	
	   public String getDateVuelta() {
		   return destYear.getSelectedItem().toString() + "-" + destMonth.getSelectedItem().toString() + "-" + destDay.getSelectedItem().toString();
	   }
	  /* IN in_clase VARCHAR(40),*/
	   public String getClaseVuelta() {
		   return ClaseVuelta;			   
	   }
	   
	   public boolean getIdaYVuelta() {
		   return idaYVuelta;
	   }
}
